import { Space, Table, Tag, Button } from 'antd';
import React, { useEffect } from 'react';
import { useState } from 'react';
import { stuDeleteApi, stuGetListApi } from '../../apis/stu';

function StuList() {
  const [data, setData] = useState([]);

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '分数',
      dataIndex: 'score',
      key: 'score',
    },
    {
      title: '城市',
      dataIndex: 'city',
      key: 'city',
    },
    {
      title: '生日',
      key: 'time',
      dataIndex: 'time',
    },
    {
      title: '操作',
      key: 'action',
      render: function (row) {
        return (
          <>
            <Button size="small" onClick={btnEvt.bind(null, 'edit', row)}>
              {' '}
              编辑
            </Button>

            <Button size="small" onClick={btnEvt.bind(null, 'delete', row)}>
              {' '}
              删除{' '}
            </Button>
          </>
        );
      },
    },
  ];

  async function btnEvt(type, row) {
    switch (type) {
      case 'edit':
        break;
      case 'delete':
        // console.log(row)
        let result = await stuDeleteApi(row.personId);

        //  console.log(result)
        // console.log(row)
        if (result.code === 200) {
          let index = data.findIndex((it) => it.personId === row.personId);

          data.splice(index, 1);
          console.log(data);
          //数组的解构
          setData([...data]);
          alert('删除数据成功');
        } else {
          alert('删除数据失败');
        }

        break;
      default:
        break;
    }
  }

  useEffect(async () => {
    let result = await stuGetListApi();
    console.log(result);
    if (result.code === 200) {
      setData(result.data);
    }
  }, []);

  return <Table columns={columns} dataSource={data} rowKey="personId" />;
}
export default StuList;
